package com.yang.core.plugins.monitoring;

import com.yang.core.model.ExceptionContext;
import com.yang.core.model.RequestContext;
import com.yang.core.model.ResponseContext;
import com.yang.core.api.RestClientInterceptor;
import com.yang.core.config.RestClientProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 指标收集拦截器
 */
@Slf4j
public class MetricsInterceptor implements RestClientInterceptor {

    private final RestClientProperties.Monitoring monitoringConfig;
    private final ConcurrentHashMap<String, AtomicLong> requestCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, AtomicLong> responseCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, AtomicLong> errorCounts = new ConcurrentHashMap<>();

    public MetricsInterceptor(RestClientProperties.Monitoring monitoringConfig) {
        this.monitoringConfig = monitoringConfig;
    }

    @Override
    public void preRequest(RequestContext context) {
        String endpoint = extractEndpoint(context);
        requestCounts.computeIfAbsent(endpoint, k -> new AtomicLong(0)).incrementAndGet();
    }

    @Override
    public void postResponse(ResponseContext context) {
        String endpoint = extractEndpointFromResponse(context);
        responseCounts.computeIfAbsent(endpoint, k -> new AtomicLong(0)).incrementAndGet();

        log.debug("指标更新 - 端点: {}, 请求次数: {}, 响应次数: {}, 状态码: {}",
                endpoint,
                requestCounts.get(endpoint).get(),
                responseCounts.get(endpoint).get(),
                context.getStatusCode());
    }

    @Override
    public void onError(ExceptionContext context) {
        String endpoint = extractEndpointFromException(context);
        errorCounts.computeIfAbsent(endpoint, k -> new AtomicLong(0)).incrementAndGet();

        log.debug("错误指标更新 - 端点: {}, 错误次数: {}, 异常类型: {}",
                endpoint,
                errorCounts.get(endpoint).get(),
                context.getException().getClass().getSimpleName());
    }

    private String extractEndpoint(RequestContext request) {
        // 简单的端点提取逻辑，可以根据需要改进
        String url = request.getUrl();
        return url.substring(url.lastIndexOf('/') + 1);
    }

    private String extractEndpointFromResponse(ResponseContext response) {
        // 简单的端点提取逻辑，可以从响应上下文中获取URL
        // 这里简化处理，返回通用值
        return "endpoint";
    }

    private String extractEndpointFromException(ExceptionContext context) {
        // 从异常上下文中获取URL
        return context.getUrl().substring(context.getUrl().lastIndexOf('/') + 1);
    }

    /**
     * 获取请求计数
     */
    public long getRequestCount(String endpoint) {
        return requestCounts.getOrDefault(endpoint, new AtomicLong(0)).get();
    }

    /**
     * 获取响应计数
     */
    public long getResponseCount(String endpoint) {
        return responseCounts.getOrDefault(endpoint, new AtomicLong(0)).get();
    }

    /**
     * 获取错误计数
     */
    public long getErrorCount(String endpoint) {
        return errorCounts.getOrDefault(endpoint, new AtomicLong(0)).get();
    }
}